"vim map key
"<Esc>esc <cr>or<CR> Enter <C-Esc> -->Ctrl-Esc <S-F1>shift+F1 <A+key> Alt+key
"vim some mode
"n		normal mode
"v		visual	mode
"o		operator mode
"!		insert mode,Command mode
"i		insert mode
"c		command mode
" :map!		list insert and command mode map
"imap,vmap,omap,nmap list same maplist
"cancel map  :unmap argv
"xxunmap argv :cancel the same map
"cancel all map  :mapclear
"autojump usage
" j  --stat
"j www_			jump to dir www　
"jc b_			jump to child dir b
"jo www_		open nautilus www
"jco b_			open child dir nautilus  b

"把vim ZZ 转换为 W --> ZZ 保存并退出 in  normal mode
map W ZZ
"把ZQ 映射为q --->ZQ 不保存并退出 in normal mode
map q ZQ
map <C-b> :NERDTree <cr>
"quit insert mode and save
imap jj <ESC>:w <CR>

" map <F4>>i{e<Esc>a}<Esc>
"imap <A-o><ESC>o
"imap <A-s><ESC>di"i
"delete current word
"imap <A-w> <ESC>ebdei
"delete current to line tail
"imap <A-u><ESC>wd$i
"use cscope source code map key
nnoremap mm <c-t>		"move move"
nnoremap mg <c-]>		"move go"
" nnoremap <silent> <<F6>>:cp<cr>
"Rset quickfix shortcut :cn:cp
"nmap
"search donw
"map <space> /
"search up
""map <c-space> ?


"git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
""""""""""""""""""""""""""""""
" Vunble
""""""""""""""""""""""""""""""
set nocompatible
filetype off " required!
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle
Plugin 'gmarik/vundle.vim'
"
Plugin 'VundleVim/Vundle.vim'

" original repos on GitHub
Plugin 'tpope/vim-fugitive'
Plugin 'Lokaltog/vim-easymotion'
Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
Plugin 'tpope/vim-rails.git'
Plugin 'tpope/vim-git'
Plugin 'tpope/vim-markdown'
Plugin 'tpope/vim-repeat'
Plugin 'godlygeek/csapprox'
Plugin 'wincent/command-t'
Plugin 'ajh17/Spacegray.vim'
Plugin 'tpope/vim-surround'
Plugin 'taglist.vim'
Plugin 'grep.vim'
Plugin 'myusuf3/numbers.vim'

"Plugin 'Lokaltog/vim-powerline'
"Plugin 'godlygeek/tabular'
Plugin 'kien/ctrlp.vim'
"plugin  'ludovicchabant/vim-lawrencium'
"Plugin 'bling/vim-airline'
Plugin 'scrooloose/syntastic'
"Plugin  'majutsushi/tabar'
"Plugin  'plasticboy/vim-markdown'
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'
Plugin 'jiangmiao/auto-pairs'
Plugin 'jlanzarotta/bufexplorer'
Plugin 'python.vim'
Plugin 'python_match.vim'
Plugin 'tomtom/tcomment_vim'
"Plugin 'tomtom/tlib_vim'
Plugin 'Valloric/python-indent'
Plugin 'Valloric/vim-valloric-colorscheme'
Plugin 'nanotech/jellybeans.vim'
""Plugin 'Yggdroot/indentLine'
Plugin 'morhetz/gruvbox'
Plugin 'hhff/SpacegrayEighties.vim'
Plugin 'a.vim'
"Plugin 'c.vim'
""vim-scripts repos
Plugin 'L9', {'name': 'newL9'}
Plugin 'FuzzyFinder'
Plugin 'Solarized'
Plugin 'molokai'
"Plugin 'scrooloose/nerdcommerter'
Plugin 'scrooloose/nerdtree'
"目录下面大的话，会出现慢
" vim-scripts repos
Plugin 'Valloric/YouCompleteMe'
Bundle 'airblade/vim-gitgutter'
"key map
nmap ]h <Plug>GitGutterNextHunk
nmap [h <Plug>GitGutterPrevHunk]
"Gitgutter不仅能显示这些git diff，还能暂存 <Leader>hs 和回退 <Leader>hr 修改。
nmap <Leader>ha <Plug>GitGutterStageHunk
nmap <Leader>hu <Plug>GitGutterRevertHunk
nmap <Leader>hv <Plug>GitGutterPreviewHunk
nmap <Leader>hr <Plug>GitGutterUndoHunk

Bundle 'croaky/vim-colors-github'
Bundle 'juvenn/mustache'
Bundle 'kana/vim-textobj-user'
Bundle 'mileszs/ack.vim'
Bundle 'rking/ag.vim'
set runtimepath^=~/.vim/bundle/ag
let g:ackprg = 'ag --nogroup --nocolor --column'
let g:ag_working_path_mode="r"
"依赖,silversearcher-ag ubuntu centos 都可以使用
"useage
"e    to open file and close the quickfix window
"o    to open (same as enter)
"go   to preview file (open but maintain focus on ag.vim results)
"t    to open in new tab
"T    to open in new tab silently
"h    to open in horizontal split
"H    to open in horizontal split silently
"v    to open in vertical split
"gv   to open in vertical split silently
"q    to close the quickfix window
Bundle 'thoughtbot/vim-rspec'
Bundle 'tpope/vim-dispatch'
Bundle 'vim-scripts/TailMinusF'
Bundle 'vim-scripts/YankRing.vim'
Bundle 'ngmy/vim-rubocop'
"r00k
Plugin 'ervandew/supertab'
Plugin 'kchmck/vim-coffee-script'
Plugin 'skwp/greplace.vim'
Plugin 'tpope/vim-bundler'
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-unimpaired'

" Clojure
Plugin 'guns/vim-clojure-static'
Plugin 'tpope/vim-classpath'
Plugin 'tpope/vim-fireplace'
"Plugin 'tpope/vim-commentary'
Plugin 'clojure-emacs/cider-nrepl'
"java completer2
Plugin 'artur-shaik/vim-javacomplete2'

" Elm
Plugin 'lambdatoast/elm.vim'

Plugin 'majutsushi/tagbar'
nmap <F4> :TagbarToggle<CR>

"scala  code highlight
Bundle 'derekwyatt/vim-scala'
"help SortScalaImports

"scala
"Plugin 'ensime/ensime-vim'
"scala config
"Typechecking after writing
"autocmd BufWritePost *.scala silent :EnTypeCheck
"Easy Type Inspection :map
nnoremap <leader>t :EnTypeCheck<CR>
"Customize the browser used for :EnDocBrowse通过设置环境变量
"export BROWSER="firefox %s"
"jump to definition cmd:EnDeclaration
au FileType scala nnoremap <leader>df :EnDeclaration<CR>
"If you want to open the declaration in a new split instead of the current buffer use :EnDeclarationSplit instead. :EnDeclarationSplit v creates a vertical split.
"more:use :h ensime

" UGgggghhhh
Plugin 'mustache/vim-mustache-handlebars'

call vundle#end()

filetype plugin indent on "required
" filetype plugin on

"needs  Plugin
"Plugin 'edsono/vim-matchit'
"Plugin 'justinmk/vim-sneak'
"Plugin 'mhizn/vim-signify'
"Plugin 'plasticboy/vim-markdown'
"Plugin 'sjl/gundo.vim'

"color schemes
"Plugin 'tomasr/molokai'
"Plugin 'flazz/vim-colorschemes'

"Plugin 'tyru/open-browser.vim'
"set shortmess+=c
" set background=light
syntax on
set nu
" 可以快速的复制多行，直接加上数字就好了
set relativenumber
set t_Co=256
set tabstop=4
set smarttab
set encoding=utf-8
set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1
" set guifont=FantasqueSansMono\ 12
set autoindent
set cindent
set incsearch
" set noet
" set sw=4

"scala doc indentation
let g:scala_scaladoc_indent = 1

" set term when running in the terminal
"if has("gui_gtk2")
"elseif
"   set term=xterm-256color
"end

" quit
command! -bang Q q<bang>

"enable powerline
let g:Powerline_symbols = 'fancy'
"colo valloric
"colo molokai
colo gruvbox
set background=dark
"colo evening

let g:ycm_confirm_extra_conf=0
let g:ycm_autoclose_preview_window_after_insertion=1
set completeopt-=preview

"ycm
let g:ycm_global_ycm_extra_conf = '~/.ycm_extra_conf.py'
" let g:ycm_extra_conf_globalist = ['~/Learning']

" let g:ycm_extra_conf_globalist = ['~/Learning', '~/*']

"backspace
set backspace=indent,eol,start

" highlight tweak
hi spellbad ctermbg=16 ctermfg=166
hi Comment ctermfg=245 guifg=#BCBCBC

" disable auto add comment mark
autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o

" fake emacs keymap
"imap <C-a> <Home>
"imap <C-e> <End>
"imap <C-f> <Right>
"imap <C-b> <Left>
"imap <C-k> <Esc>d$<C-c>A
"imap <C-d> <delete>
"imap <C-n> <Down>
"imap <C-p> <Up>

" steal configs

" nnoremap ; :
" nnoremap : ;
" vnoremap ; :
" vnoremap : ;


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                           reset vimrc augroup                           "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" We reset the vimrc augroup. Autocommands are added to this group throughout
" the file
augroup vimrc
  autocmd!
augroup END

set scrolloff=2         " 2 lines above/below cursor when scrolling
set showmatch           " show matching bracket (briefly jump)
" set matchtime=2         " reduces matching paren blink time from the 5[00]ms def
set showmode            " show mode in status bar (insert/replace/...)
set showcmd             " show typed command in status bar
set ruler               " show cursor position in status bar
set nowrap				"no warp file"
set title               " show file in titlebar"
" set undofile            " stores undo state even when files are closed (in undodir)
set cursorline          " highlights the current line
set winaltkeys=no       " turns of the Alt key bindings to the gui menu


" When you type the first tab, it will complete as much as possible, the second
" tab hit will provide a list, the third and subsequent tabs will cycle through
" completion options so you can complete the file without further keys
set wildmode=longest,list,full
set wildmenu            " completion with menu
" This changes the default display of tab and CR chars in list mode
set listchars=tab:▸\ ,eol:¬

" The "longest" option makes completion insert the longest prefix of all
" the possible matches; see :h completeopt
set completeopt=menu,menuone,longest
set switchbuf=useopen,usetab"

" EDITOR SETTINGS
set ignorecase
set smartcase
set autoindent
set copyindent
set cindent
set cino=b1,g0,N-s,t0,(0,W4  " see :h cinoptions-values
set smarttab            " smart tab handling for indenting
set magic               " change the way backslashes are used in search patterns
set bs=indent,eol,start " Allow backspacing over everything in insert mode
set nobackup            " no backup~ files.

set tabstop=4           " number of spaces a tab counts for
set shiftwidth=4        " spaces for autoindents
set softtabstop=4
set shiftround          " makes indenting a multiple of shiftwidth
set expandtab           " turn a tab into spaces
"set noshowmode          " don't show the mode ("-- INSERT --") at the bottom

" misc settings
set fileformat=unix     " file mode is unix
set fileformats=unix,dos,mac   " detects unix, dos, mac file formats in that order

set viminfo='20,\"500   " remember copy registers after quitting in the .viminfo
                        " file -- 20 jump links, regs up to 500 lines'

set hidden              " allows making buffers hidden even with unsaved changes
set history=10000       " remember more commands and search history
set undolevels=1000     " use many levels of undo
set autoread            " auto read when a file is changed from the outside
set mouse=a             " enables the mouse in all modes
set foldlevelstart=99   " all folds open by default

" toggles vim's paste mode; when we want to paste something into vim from a
" different application, turning on paste mode prevents the insertion of extra
" whitespace
set pastetoggle=<F7>

" Right-click on selection should bring up a menu
set mousemodel=popup_setpos

" With this, the gui (gvim and macvim) now doesn't have the toolbar, the left
" and right scrollbars and the menu.
set guioptions-=T
set guioptions-=l
set guioptions-=L
set guioptions-=r
set guioptions-=R
set guioptions-=m
set guioptions-=M

" this makes sure that shell scripts are highlighted
" as bash scripts and not sh scripts
let g:is_posix = 1

" tries to avoid those annoying "hit enter to continue" messages
" if it still doesn't help with certain commands, add a second <cr>
" at the end of the map command
set shortmess+=a

" Look for tag def in a "tags" file in the dir of the current file, then for
" that same file in every folder above the folder of the current file, until the
" root.
set tags=./tags;

" turns off all error bells, visual or otherwise
set noerrorbells visualbell t_vb=
autocmd vimrc GUIEnter * set visualbell t_vb=

" none of these should be word dividers, so make them not be
set iskeyword+=_,$,@,%,#,-      "带有左侧符号的单词不要被换行分割

" allow backspace and cursor keys to cross line boundaries
set whichwrap+=<,>,h,l
set nohlsearch          " do not highlight searched-for phrases
"set hlsearch
set incsearch           " ...but do highlight-as-I-type the search string
set gdefault            " this makes search/replace global by default

" enforces a specified line-length and auto inserts hard line breaks when we
" reach the limit; in Normal mode, you can reformat the current paragraph with
" gqap.

"set textwidth=180

" this makes the color after the textwidth column highlighted
" set colorcolumn=+1

" options for formatting text; see :h formatoptions
set formatoptions=tcroqnj

if v:version >= 704
  " The new Vim regex engine is currently slooooow as hell which makes syntax
  " highlighting slow, which introduces typing latency.
  " Consider removing this in the future when the new regex engine becomes
  " faster.
  set regexpengine=1
endif

" The alt (option) key on macs now behaves like the 'meta' key. This means we
" can now use <m-x> or similar as maps. This is buffer local, and it can easily
" be turned off when necessary (for instance, when we want to input special
" characters) with :set nomacmeta.
if has("gui_macvim")
  set macmeta
endif

"if has('unnamedplus')
  " By default, Vim will not use the system clipboard when yanking/pasting to
  " the default register. This option makes Vim use the system default
  " clipboard.
  " Note that on X11, there are _two_ system clipboards: the "standard" one, and
  " the selection/mouse-middle-click one. Vim sees the standard one as register
  " '+' (and this option makes Vim use it by default) and the selection one as
  " '*'.
  " See :h 'clipboard' for details.
  " set clipboard=unnamedplus,unnamed
" else
  " Vim now also uses the selection system clipboard for default yank/paste.
  "set clipboard+=unnamed
" endif

" UltiSnips is missing a setf trigger for snippets on BufEnter
autocmd vimrc BufEnter *.snippets setf snippets

" In UltiSnips snippet files, we want actual tabs instead of spaces for indents.
" US will use those tabs and convert them to spaces if expandtab is set when the
" user wants to insert the snippet.
autocmd vimrc FileType snippets set noexpandtab

" The stupid python filetype plugin overrides our settings!
autocmd vimrc FileType python
      \ set tabstop=4 |
      \ set shiftwidth=4 |
      \ set softtabstop=4 |
      " \ nnoremap ; :|
      " \ nnoremap : ;|
      " \ vnoremap ; :|
      " \ vnoremap : ;|
      " \ inoremap ; :|
      " \ inoremap : ;

" The stupid rust filetype plugin overrides our settings!
autocmd vimrc FileType rust
      \ set tabstop=4 |
      \ set shiftwidth=4 |
      \ set softtabstop=4 |
      \ set textwidth=80

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                           More involved tweaks                          "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Unicode support (taken from http://vim.wikia.com/wiki/Working_with_Unicode)
if has("multi_byte")
  if &termencoding == ""
    let &termencoding = &encoding
  endif
  set encoding=utf-8
  setglobal fileencoding=utf-8
  set fileencodings=ucs-bom,utf-8,latin1
endif

augroup vimrc
  " Automatically delete trailing DOS-returns and whitespace on file open and
  " write.
  autocmd BufRead,BufWritePre,FileWritePre * silent! %s/[\r \t]\+$//
augroup END


" Sets a font for the GUI
if has("gui_gtk2")
  set guifont=Source\ Code\ Pro\ For\ Powerline\ Medium\ 12
elseif has("gui_macvim")
  " My Mac has a fairly high DPI so the font needs to be bigger
  set guifont=Consolas\ For\ Powerline:h14
elseif has("gui_win32")
  set guifont=Consolas\ For\ Powerline:h11
end

" Sometimes, $MYVIMRC does not get set even though the vimrc is sourced
" properly. So far, I've only seen this on Linux machines on rare occasions.
if has("unix") && strlen($MYVIMRC) < 1
  let $MYVIMRC=$HOME . '/.vimrc'
endif

" Highlight Class and Function names
function! s:HighlightFunctionsAndClasses()
  syn match cCustomFunc      "\w\+\s*\((\)\@="
  syn match cCustomClass     "\w\+\s*\(::\)\@="

  hi def link cCustomFunc      Function
  hi def link cCustomClass     Function
endfunction

" Highlight Class and Function names, D specific
function! s:HighlightDFunctionsAndClasses()
  syn match cCustomDFunc     "\w\+\s*\(!.\{-}(\)\@="
  syn match cCustomDFuncUFCS ".\w\+\s*\(!.\{-}\)\@="

  hi def link cCustomDFunc     Function
  hi def link cCustomDFuncUFCS Function
endfunction

" TODO: this should:
" a) not be called for every filetype
" b) be in a separate plugin
au vimrc Syntax * call s:HighlightFunctionsAndClasses()
au vimrc Syntax d call s:HighlightDFunctionsAndClasses()

" TODO: split this into separate plugin
function! VisualSearch(direction) range
    let l:saved_reg = @"
    execute "normal! vgvy"

    let l:pattern = escape(@", '\\/.*$^~[]')
    let l:pattern = substitute(l:pattern, "\n$", "", "")

    if a:direction == 'b'
        execute "normal ?" . l:pattern . "^M"
    elseif a:direction == 'gv'
        execute "Ack " . l:pattern . ' %'
    elseif a:direction == 'f'
        execute "normal /" . l:pattern . "^M"
    endif

    let @/ = l:pattern
    let @" = l:saved_reg
endfunction

"Basically you press * or # to search for the current selection
" * is next search
" # is up search
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
vnoremap <silent> gv :call VisualSearch('gv')<CR>

" cindent is a bit too smart for its own good and triggers in text files when
" you're typing inside parens and then hit enter; it aligns the text with the
" opening paren and we do NOT want this in text files!
autocmd vimrc FileType text,markdown,gitcommit set nocindent

autocmd vimrc FileType markdown setlocal spell! spelllang=en_us

au vimrc BufReadCmd *.epub call zip#Browse( expand( "<amatch>" ) )

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                            custom mappings                              "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" NOTE: a lot of these mappings won't make sense until you realize I'm using a
" "Dvorak-Qwerty Command" layout (and similar on Win/Lin). The layout is Dvorak
" unless you hold down Ctrl or Alt or Cmd; then it changes to Qwerty. This type
" of layout gives us Dvorak typing but Qwerty keyboard shortcuts.

" our <leader> will be the space key
let mapleader=" "

" our <localleader> will be the '-' key
let maplocalleader="-"

" this makes vim's regex engine "not stupid"
" see :h magic
nnoremap / /\v
vnoremap / /\v

" With this map, we can select some text in visual mode and by invoking the map,
" have the selection automatically filled in as the search text and the cursor
" placed in the position for typing the replacement text. Also, this will ask
" for confirmation before it replaces any instance of the search text in the
" file.
" NOTE: We're using %S here instead of %s; the capital S version comes from the
" eregex.vim plugin and uses Perl-style regular expressions.
vnoremap <C-r> "hy:%S/<C-r>h//c<left><left>

" Fast saving
nnoremap <leader>w :w!<cr>


" cancel all space line for file
nnoremap <leader>lc :g/^s*$/d<cr>


"make file
nnoremap <leader>ma :make<cr>
nmap <<F6>>:cn<cr>			"next
nmap <<F7>>:cp<cr>			"previous

" <leader>v brings up .vimrc
" <leader>V reloads it and makes all changes active (file has to be saved first)
noremap <leader>v :e! $MYVIMRC<CR>
noremap <silent> <leader>V :source $MYVIMRC<CR>:filetype detect<CR>:exe ":echo 'vimrc reloaded'"<CR>

" with this, we can now type ",." to exit out of insert mode
" if we really wanted to type ",.", then just type one char, wait half a sec,
" type another
"inoremap ,. <Esc>
"vnoremap ,. <Esc>

" CTRL-U and CTRL-W in insert mode cannot be undone.  Use CTRL-G u to first
" break undo, so that we can undo those changes after inserting a line break.
" For more info, see: http://vim.wikia.com/wiki/Recover_from_accidental_Ctrl-U
inoremap <c-u> <c-g>u<c-u>
inoremap <c-w> <c-g>u<c-w>

" This command will allow us to save a file we don't have permission to save
" *after* we have already opened it. Super useful.
cnoremap w!! w !sudo tee % >/dev/null

" Swap implementations of ` and ' jump to markers
" By default, ' jumps to the marked line, ` jumps to the marked line and
" column, so swap them
" nnoremap ' `
" nnoremap ` '

" g<c-]> is jump to tag if there's only one matching tag, but show list of
" options when there is more than one definition
nnoremap <leader>g g<c-]>

"this need to ruby
"nnoremap <leader>t <c-t>

" These create newlines like o and O but stay in normal mode
"produce newlines down
nnoremap <silent> zj o<Esc>k
"produce newlines up
nnoremap <silent> zk O<Esc>j


" Now we don't have to move our fingers so far when we want to scroll through
" the command history; also, don't forget the q: command (see :h q: for more
" info)
cnoremap <c-j> <down>
cnoremap <c-k> <up>

" Keep search matches in the middle of the window.
" zz centers the screen on the cursor, zv unfolds any fold if the cursor
" suddenly appears inside a fold.
nnoremap * *zzzv
nnoremap # #zzzv
nnoremap n nzzzv
nnoremap N Nzzzv

" Also center the screen when jumping through the changelist
nnoremap g; g;zz
nnoremap g, g,zz

" In normal mode, we use : much more often than ; so lets swap them.
" WARNING: this will cause any "ordinary" map command without the "nore" prefix
" that uses ":" to fail. For instance, "map <f2> :w" would fail, since vim will
" read ":w" as ";w" because of the below remappings. Use "noremap"s in such
" situations and you'll be fine.
" nnoremap ; :
" nnoremap : ;
" vnoremap ; :
" vnoremap : ;

" This makes j and k work on "screen lines" instead of on "file lines"; now, when
" we have a long line that wraps to multiple screen lines, j and k behave as we
" expect them to.
nnoremap j gj
nnoremap k gk


" Default mapping
let g:multi_cursor_next_key='<C-n>'
let g:multi_cursor_prev_key='<C-p>'
let g:multi_cursor_skip_key='<C-x>'
let g:multi_cursor_quit_key='<Esc>'





" Use Q for formatting the current paragraph (or visual selection)
vnoremap Q gq
nnoremap Q gqap

" This is quit all
noremap <Leader>q :qa<cr>

" key bindings for quickly moving between windows
" h left, l right, k up, j down
noremap <leader>h <c-w>h
noremap <leader>l <c-w>l
noremap <leader>k <c-w>k
noremap <leader>j <c-w>j

" for faster scrolling
" TODO: create a command for scrolling by ~70% of the window height
"noremap <m-j> 15gj
"noremap <m-k> 15gk

" on macs the alt key is inconvenient to press, so let's also map to ctrl
noremap <c-j> 15gj
noremap <c-k> 15gk

" Switches to the previous buffer that was shown in the current window, but also
" closes the current buffer before switching to the previous one
noremap <leader>bq <c-^> :bd #<cr>

" Switch to the directory of the open buffer
noremap <leader>cd :cd %:p:h<cr>

" Toggle and untoggle spell checking
noremap <leader>ss :setlocal spell! spelllang=en_us<cr>

" spelling shortcuts using <leader>
" ]s next misspelled word
" [s previous misspelled word
" zg add to dict
" z= get suggestions
noremap <leader>sn ]s
noremap <leader>sp [s
noremap <leader>sa zg
noremap <leader>su z=

" Using '<' and '>' in visual mode to shift code by a tab-width left/right by
" default exits visual mode. With this mapping we remain in visual mode after
" such an operation.
vnoremap < <gv
vnoremap > >gv

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                               Command-T                                 "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

let g:CommandTMaxHeight = 30
let g:CommandTMatchWindowReverse = 1 " shows results in reverse order
let g:CommandTFileScanner = 'find'
let g:CommandTTraverseSCM = 'pwd'

set wildignore+=*.o,*.obj,.git,*.pyc,*.so,blaze*,READONLY,llvm,Library*
set wildignore+=CMakeFiles,packages/*,**/packages/*,**/node_modules/*

" This appears to be necessary; command-t doesn't appear to be falling back to
" wildignore on its own.
let g:CommandTWildIgnore=&wildignore

" MacVim doesn't use tab focus to switch from command-t input field to the file
" list, so using j and k for next and prev screws everything up. But it does
" work on linux so let's use it there.
if has("gui_gtk2")
    let g:CommandTSelectNextMap = [ '<down>' ]
    let g:CommandTSelectPrevMap = [ '<up>' ]
endif

nnoremap <leader>t :CommandT<cr>
nnoremap <leader>n :CommandTBuffer<cr>
nnoremap <leader>' :CommandTFlush<cr>

let g:CommandTCancelMap = ['<ESC>', '<C-c>']

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                                UltiSnips                                "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" we can't use <tab> as our snippet key since we use that with YouCompleteMe
let g:UltiSnipsSnippetsDir         = $HOME.'/.vim/bundle/vim-snippets/UltiSnips'
if has("gui_macvim")
  " Ctrl conflicts with "Dvorak-Qwerty Command"
   let g:UltiSnipsExpandTrigger       = "<m-s>"
else
  " Alt conflicts with Xmonad
   let g:UltiSnipsExpandTrigger       = "<c-s>"
endif
"let g:UltiSnipsExpandTrigger       = "<c-s>"
"complete for loop  --  class
let g:UltiSnipsExpandTrigger       = "<c-j>"
let g:UltiSnipsListSnippets        = "<c-m-s>"
let g:UltiSnipsJumpForwardTrigger  = "<c-f>"
let g:UltiSnipsJumpBackwardTrigger = "<c-b>"
let g:snips_author                 = 'Strahinja Val Markovic'

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                               easymotion                                "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

let g:EasyMotion_leader_key = '<Leader>e'

" Provides the equivalent of <Leader>s, which is forwards/backwards search for a
" character.
" has to be 'nmap', 'noremap' doesn't work
nmap s <Plug>(easymotion-s)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                              fuzzyfinder                                "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" This turns on the mrufile and mrucmd modes
let g:fuf_modesDisable    = []
let g:fuf_mrufile_maxItem = 1000
let g:fuf_mrucmd_maxItem  = 400
let g:fuf_file_exclude    = '\v\~$|\.(o|exe|dll|bak|class|meta|lock|orig|jar|swp)$|/test/data\.|(^|[/\\])\.(hg|git|bzr)($|[/\\])'

nnoremap <Leader>fm :FufMruFile<CR>
nnoremap <Leader>fc :FufMruCmd<CR>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                                vim-git                                  "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Turn on spell checking by default for git commit messages
au vimrc FileType gitcommit setlocal spell! spelllang=en_us

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                                syntastic                                "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

let g:syntastic_error_symbol = 'x'
let g:syntastic_warning_symbol = '!'
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_python_checkers = ['flake8']
let g:syntastic_python_flake8_args = '--select=F,C9 --max-complexity=10'

let g:syntastic_mode_map = {
       \ "mode": "active",
       \ "active_filetypes": [],
       \ "passive_filetypes": ["dart", "html"] }


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                              YouCompleteMe                              "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:ycm_collect_identifiers_from_tags_files = 1			 "开启基于tag的补全可以在这添path
let g:ycm_complete_in_comments = 1                           "comment also complete
let g:ycm_complete_in_sting = 1                              "chars aslo complete
let g:ycm_collect_identifiers_from_comment_and_string = 0    "comment and chars word also complete
let g:ycm_autoclose_preview_window_after_completion = 1
let g:ycm_min_num_identifier_candidate_chars = 4
" let g:ycm_extra_conf_globlist = ['~/Learning/*']
let g:ycm_filetype_specific_completion_to_disable = {'javascript': 1}
let g:ycm_seed_identifiers_with_syntax = 1                  "syntax keyword complete
let g:ycm_confirm_extra_conf = 0
let g:ycm_autoclose_preview_window_after_insertion=1
let g:ycm_key_list_select_completion = ['<TAB>', '<Down>']
"let g:ycm_key_list_previous_completion =  ['<c-p>']
let g:ycm_key_list_previous_completion =  ['<Up>']
let g:ycm_min_num_of_chars_for_complettion =  2				""输入第二个字符开始补全

""""""""""""YCM""""""""""""""""""""
filetype plugin indent on
nnoremap <leader>y :YcmForceCompileAndDiagnostics<cr>
nnoremap <leader>pg :YcmCompleter GoTo<CR>
nnoremap <leader>pd :YcmCompleter GoToDefinition<CR>
nnoremap <leader>pc :YcmCompleter GoToDeclaration<CR>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                                Airline                                  "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

let g:airline_powerline_fonts = 0
let g:airline_theme = 'jellybeans'



"this my vimrc
"colo evening
"auto smart indent
set smartindent
set noexpandtab
"cmd height
set cmdheight=2

""""""""""""""""""""""cscope设置""""""""""""""""""
"indentLine
"set viminfo+=!
"let g:indentLine_char = '|'
set cscopequickfix=s-,c-,d-,i-,t-,e-
"nmap <C-n>:cnext<CR>
"nmap <C-p>:cprev<CR>
if has("cscope")
	set csprg=/usr/bin/cscope
	set csto=0
	set cst
	set nocsverb
"如果打开不高亮 export CSCOPE_EDITOR=vim or open ~/.bashrc 添加
	" add any database in current directory
	if filereadable("cscope.out")
		cs add cscope.out
	endif
	set csverb
endif


"cs find c|d|e|f|g|i|s|t name
"0 或 s 查找本 C 符号(可以跳过注释)
"1 或 g 查找本定义
"2 或 d 查找本函数调用的函数
"3 或 c 查找调用本函数的函数
"4 或 t 查找本字符串
"6 或 e 查找本 egrep 模式
"7 或 f 查找本文件
"8 或 i 查找包含本文件的文件
"nmap <C-@>s :cs find s <C-R>=expand("<cword>")<CR><CR>:copen<CR>
"nmap <C-@>g :cs find g <C-R>=expand("<cword>")<CR><CR>
"nmap <C-@>c :cs find c <C-R>=expand("<cword>")<CR><CR>:copen<CR>
"nmap <C-@>t :cs find t <C-R>=expand("<cword>")<CR><CR>:copen<CR>
"nmap <C-@>e :cs find e <C-R>=expand("<cword>")<CR><CR>:copen<CR>
"nmap <C-@>f :cs find f <C-R>=expand("<cfile>")<CR><CR>:copen<CR>
"nmap <C-@>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>:copen<CR>
"nmap <C-@>d :cs find d <C-R>=expand("<cword>")<CR><CR>:copen<CR>

nmap cs f s :cs find s =expand("")
nmap cs f g :cs find g =expand("")
nmap cs f c :cs find c =expand("")
nmap cs f t :cs find t =expand("")
nmap cs f e :cs find e =expand("")
nmap cs f f :cs find f =expand("")
nmap cs f i :cs find i ^=expand("")$
nmap cs f d :cs find d =expand("")

let g:winManagerWindowLayout='FileExplorer|Taglist'
nmap wm :WMToggle<CR>
"只剩下一个win就退出
let g:persisternBehaviour=0



filetype plugin indent on

"""""""""""""""""Taglist设置"""""""""""""""""
""let Tlist_Auto_Open = 1
" let Tlist_Ctags_Cmd = '/usr/bin/ctags'			" centos"
let Tlist_Ctags_Cmd = '/usr/bin/ctags'  "ubuntu"
let Tlist_Exit_OnlyWindow = 1
" 按F3按钮，在窗口的左侧出现taglist的窗口,像vc的左侧的workpace
"nnoremap <silent> <F3> :TlistToggle<CR>
nnoremap <silent> <Leader>tl :TlistToggle<CR>
" :Tlist              调用TagList
let Tlist_Show_One_File=1	 "显示多个文件的tags
"let Tlist_Exit_OnlyWindow=1 "如果Taglist窗口是最后一个窗口则退出Vim
let Tlist_Use_Right_Window=1 " 在右侧窗口中显示
let Tlist_File_Fold_Auto_Close=1             " 自动折叠


"ctags
set tags=tags;
set autochdir

"               my    vimrc
"
"imap <C-l> :<Space>
"nnoremap <cr>G
"nnoremap <leader>gg

"open current file

"show tab space
set list listchars=tab:→\ ,trail:·
" comment auto
"<leader>cc comment in the normal or visual
"<leader>cu cancel comment
"<leader>c<space>
"first copy and comment
"<leader>cy
"when comment ,auto add space
let g:NERDSpaceDelims=1

"use leader o replace c+p
"nnoremap <leader>o :CtrlP<CR>
"inoremap <Tab> <C-P>
nmap <leader><Leader> v
"set highlightsearch
set hls
"cancel highlight
" imap <C-h> :nohl<CR>
map <C-h> :nohl<CR>
"map <A-/> :nohl<CR>
"imap <A-/><Esc><A-/>i
"设置自动缩进
set ai
set si
"cursor location last modify place"
if has ("autocmd")
        au BufReadPost * if line("'\"")>1|if line("'\"")<=line("$") | exe ("norm'\"") |else |exe "norm $"|endif|endif
endif

"show status in the window bottom
"set statusline=%F%m%r%w%h[Format=%{&ff}][Type=%Y]%{strftime(\"%d/%m/%y---%H:%M\")}%=[L:%l,Col:%c][%p%%]
set statusline=%F%m%r%w%h[Format=%{&ff}][Type=%Y]%{strftime(\"%d/%m/%y---%H:%M\")}%=[pos:%o\,ASCII:%b\,0x%B,Row:%l,Col:%c][%p%%]
set laststatus=2

"set paste                  "这里的设置会tab补全产生conflict 以至于tab 失效"
"" no swap
set noswapfile
set wrap
set nocp
"整词换行
set linebreak
"光标快速跳动
set whichwrap=b,s,<,>,[,]

" <A-u><Esc>ebdei





"auto comment perl file
autocmd BufNewfile *.pl exec ":call SetPerlTitle()"
func SetPerlTitle()
        call setline(1,"\#################################")
        call append(line("."),"\#     File name   :".expand("%"))
        call append(line(".")+1,"\#     Author      :kangkangliang")
        call append(line(".")+2,"\#     File desc   :")
        call append(line(".")+3,"\#     Mail        :liangkangkang@yahoo.com")
        call append(line(".")+4,"\#     Create time :".strftime("%Y-%m-%d",localtime()))
        call append(line(".")+5,"\#################################")
        call append(line(".")+6,"#!/usr/bin/perl ")
        call append(line(".")+7,"use strict;")
        call append(line(".")+8,"use warnings;")
        call append(line(".")+9,"")
endfunc

"auto comment python file
autocmd BufNewfile *.py exec ":call SetPythonTitle()"
func SetPythonTitle()
        call setline(1,"\#################################")
        call append(line("."),"\#-*- coding: utf-8 -*-"          )
        call append(line(".")+1,"\#     File name   :".expand("%"))
        call append(line(".")+2,"\#     Author      :kangkangliang")
        call append(line(".")+3,"\#     File desc   :")
        call append(line(".")+4,"\#     Mail        :liangkangkang@yahoo.com")
        call append(line(".")+5,"\#     Create time :".strftime("%Y-%m-%d",localtime()))
        call append(line(".")+6,"\#################################")
        call append(line(".")+7,"#!/usr/bin/env python ")
        call append(line(".")+8,"import os")
        call append(line(".")+9,"import numpy as np")
        call append(line(".")+10,"import matplotlib.pyplot as plt")
        call append(line(".")+11,"import sys")
        call append(line(".")+12,"")
endfunc

"auto comment scala file
autocmd BufNewfile *.scala exec ":call SetScalaTitle()"
func SetScalaTitle()
        call setline(1,"/**")
        call append(line("."),"\ *"          )
        call append(line(".")+1,"\ *     File name   :".expand("%"))
        call append(line(".")+2,"\ *     Author      :kangkangliang")
        call append(line(".")+3,"\ *     File desc   :")
        call append(line(".")+4,"\ *     Mail        :liangkangkang@yahoo.com")
        call append(line(".")+5,"\ *     Create time :".strftime("%Y-%m-%d",localtime()))
        call append(line(".")+6,"**/")
        call append(line(".")+7,"")
        call append(line(".")+8,"")
        call append(line(".")+9,"")
        call append(line(".")+10,"object {")
        call append(line(".")+11,"	def main(args: Array[String]) {")
        call append(line(".")+12,"")
        call append(line(".")+13,"	}")
        call append(line(".")+14,"}")
        call append(line(".")+15,"")
endfunc

"auto comment java file
autocmd BufNewfile *.java exec ":call SetJavaTitle()"
func SetJavaTitle()
        call setline(1,"/**")
        call append(line("."),"\ *"          )
        call append(line(".")+1,"\ *     File name   :".expand("%"))
        call append(line(".")+2,"\ *     Author      :kangkangliang")
        call append(line(".")+3,"\ *     File desc   :")
        call append(line(".")+4,"\ *     Mail        :liangkangkang@yahoo.com")
        call append(line(".")+5,"\ *     Create time :".strftime("%Y-%m-%d",localtime()))
        call append(line(".")+6,"**/")
        call append(line(".")+7,"")
        call append(line(".")+8,"")
        call append(line(".")+9,"")
        call append(line(".")+10,"public class  {")
        call append(line(".")+11,"	public static void main(String args[]) {")
        call append(line(".")+12,"")
        call append(line(".")+13,"	}")
        call append(line(".")+14,"}")
        call append(line(".")+15,"")
endfunc

autocmd BufNewfile *.sh,*.[ch],*.cpp exec ":call SetTitle()"
autocmd BufNewFile * normal G  "新建文件后，自动定位到文件末尾
func SetTitle()
        if &filetype == 'sh'
                call setline(1,"\#########################################")
                call append(line("."),"\#         File name   :".expand("%"))
                call append(line(".")+1,"\#         Author      :kangkangliang")
                call append(line(".")+2,"\#         File desc   :")
                call append(line(".")+3,"\#         Mail        :liangkangkang@yahoo.com")
                call append(line(".")+4,"\#         Create time :".strftime("%Y-%m-%d",localtime()))
                call append(line(".")+5,"\#########################################")
                call append(line(".")+6,"\#!/usr/bin/bash")
                call append(line(".")+7,"")
        else
                call setline(1,"/**")
                call append(line("."),"\ *            File name               :".expand("%"))
                call append(line(".")+1,"\ *            Author                  :kangkangliang")
                call append(line(".")+2,"\ *            File desc               :")
                call append(line(".")+3,"\ *            Mail                    :liangkangkang@yahoo.com")
                call append(line(".")+4,"\ *            Create time             :".strftime("%Y-%m-%d",localtime()))
                call append(line(".")+5,"\ */")
        endif
        if &filetype == 'lua'
                call setline(1,"\#########################################")
                call append(line("."),"\#         File name   :".expand("%"))
                call append(line(".")+1,"\#         Author      :kangkangliang")
                call append(line(".")+2,"\#         File desc   :")
                call append(line(".")+3,"\#         Mail        :liangkangkang@yahoo.com")
                call append(line(".")+4,"\#         Create time :".strftime("%Y-%m-%d",localtime()))
                call append(line(".")+5,"\#########################################")
                call append(line(".")+6,"\#!/usr/bin/lua")
                call append(line(".")+7,"")
        endif
        if &filetype == 'cpp'
				call append(line(".")+6,"")
                call append(line(".")+7,"/**")
                call append(line(".")+8," *                                             headfile")
                call append(line(".")+9," */")
                call append(line(".")+10,"#include <iostream>")
                call append(line(".")+11,"#include <fstream>")
                call append(line(".")+12,"#include <vector>")
                call append(line(".")+13,"#include <string>")
                call append(line(".")+14,"")
                call append(line(".")+15,"#include <iterator>")
                call append(line(".")+16,"")
                call append(line(".")+17,"")
                call append(line(".")+18,"")
                call append(line(".")+19,"#include <opencv2/core/core.hpp>")
                call append(line(".")+20,"")
                call append(line(".")+21,"")
                call append(line(".")+22,"")
                call append(line(".")+23,"")
                call append(line(".")+24,"#include <opencv2/imgproc/imgproc.hpp> ")
                call append(line(".")+25,"#include <opencv2/highgui/highgui.hpp>")
                call append(line(".")+26,"using namespace std;")
                call append(line(".")+27,"using namespace cv;")
                call append(line(".")+28,"using namespace cv::cuda;")
                call append(line(".")+29,"/**")
                call append(line(".")+30," *                                            main function")
                call append(line(".")+31," */")
                call append(line(".")+32,"int")
                call append(line(".")+33,"main(int argc,char **argv)")
                call append(line(".")+34,"{")
                call append(line(".")+35,"")
                call append(line(".")+36,"    return 0;")
                call append(line(".")+37,"}")
        endif
        if &filetype == 'c'
                call append(line(".")+6,"")
                call append(line(".")+7,"/**")
                call append(line(".")+8," *                     headfile")
                call append(line(".")+9," */")
                call append(line(".")+10,"#include <stdio.h>")
                call append(line(".")+11,"#include <stdlib.h>")
                call append(line(".")+12,"")
                call append(line(".")+13,"/**")
                call append(line(".")+14," *                    main function")
                call append(line(".")+15," */")
                call append(line(".")+16,"int")
                call append(line(".")+17,"main(int argc,char **argv)")
                call append(line(".")+18,"{")
                call append(line(".")+19,"")
                call append(line(".")+20,"    return 0;")
                call append(line(".")+21,"}")
        endif
endfun

" ------------------------------------------------------------------------------
" 程序的编译运行
" ------------------------------------------------------------------------------
"C，C++ 按F5编译运行
map <F5> :call CompileRunGcc()<CR>
func! CompileRunGcc()
    exec "w"
    if &filetype == 'c'
        exec "!gcc % -o %<"
        exec "!./%<"
    elseif &filetype == 'cpp'
        exec "!g++ % -o %<"
        exec "!./%<"
    elseif &filetype == 'java'
        exec "!javac %"
        exec "!java %<"
    elseif &filetype == 'sh'
        :!./%
    elseif &filetype == 'python'
    	exec "!python %"
    elseif &filetype == 'perl'
    	exec "!perl %"
    elseif &filetype == 'scala'
    	exec "!scala %"
    endif
endfunc
"C,C++的调试
map <F8> :call Rungdb()<CR>
func! Rungdb()
    exec "w"
    if &filetype == 'python'
    	exec "!ipdb %"
	elseif &filetype == 'c'
		exec "!gcc % -g -o %<"
		exec "!gdb ./%<"
	elseif &filetype == 'cpp'
		exec "!g++ % -g -o %<"
		exec "!gdb ./%<"
endfunc


" ------------------------------------------------------------------------------
" F3自动插入函数注释
" ------------------------------------------------------------------------------
map <F3> :call SetFuncNotes()<CR>
func SetFuncNotes()
    if &filetype == 'sh'
        call append(line("."), "# @brief   ")
        call append(line(".")+1, "# @inputs  ")
        call append(line(".")+2, "# @outputs ")
        call append(line(".")+3, "# @retval  ")
    elseif &filetype == 'matlab'
        call append(line("."), "% @brief   ")
        call append(line(".")+1, "% @inputs  ")
        call append(line(".")+2, "% @outputs ")
        call append(line(".")+3, "% @retval  ")
    else
        call append(line("."), "/**")
        call append(line(".")+1, " * @param")
        call append(line(".")+2, " * @param")
        call append(line(".")+3, " * @param")
        call append(line(".")+4, " * @param")
        call append(line(".")+5, " */")
    endif
endfunc
"set foldenable                  "允许折叠
"set foldmethod=indent           "折叠方式,包括indent,manual,marker等

"add another config
" Emacs-like beginning and end of line.
imap <c-e> <c-o>$
imap <c-a> <c-o>^
"set bg=light
" Highlight the status line
highlight StatusLine ctermfg=black ctermbg=yellow
" Quickfix management
"map <Space><Space> :ccl<cr>
" Merge a tab into a split in the previous window
function! MergeTabs()
  if tabpagenr() == 1
    return
  endif
  let bufferName = bufname("%")
  if tabpagenr("$") == tabpagenr()
    close!
  else
    close!
    tabprev
  endif
  split
  execute "buffer " . bufferName
endfunction

nmap <C-W>u :call MergeTabs()<CR>
" Use Silver Searcher instead of grep
set grepprg=ag
"set wmh=0
"set viminfo+=!
"set guioptions-=T
"set guifont=Triskweline_10:h10
"set et
"set sw=2
"set smarttab
"set noincsearch
"set gdefault " assume the /g flag on :s substitutions to replace all matches in a line
"set autoindent " always set autoindenting on
"set lazyredraw " Don't redraw screen when running macros.


" Format xml files
au FileType xml exe ":silent 1,$!xmllint --format --recover - 2>/dev/null"

set nofoldenable " Say no to code folding...

au BufNewFile,BufRead *.txt setlocal nolist " Don't display whitespace


"imap <C-l> :<Space>

"ctrl + m new a label page
map <C-m> <esc>:tabnew<CR>

"install Plugin
"map <Leader>bb :!BundleInstall<cr>
" ================
"map <Leader>ac :sp app/controllers/application_controller.rb<cr>
"vmap <Leader>b :<C-U>!git blame <C-R>=expand("%:p") <CR> \| sed -n <C-R>=line("'<") <CR>,<C-R>=line("'>") <CR>p <CR>
"nmap <Leader>bi :source ~/.vimrc<cr>:PluginInstall<cr>
"vmap <Leader>bed "td?describe<cr>obed<tab><esc>"tpkdd/end<cr>o<esc>:nohl<cr>
"map <Leader>cc :!cucumber --drb %<CR>
"map <Leader>cu :Tabularize /\|<CR>
"map <Leader>co mmggVG"*y`m
"map <Leader>cc :Rjcollection client/
"map <Leader>cj :Rjspec client/
"map <Leader>cm :Rjmodel client/
"map <Leader>cs :call SearchForCallSitesCursor()<CR>
"map <Leader>ct :Rtemplate client/
"map <Leader>cv :Rjview client/
"map <Leader>cn :e ~/Dropbox/notes/coding-notes.txt<cr>
"map <Leader>d orequire 'pry'<cr>binding.pry<esc>:w<cr>
"map <Leader>dr :e ~/Dropbox<cr>
"map <Leader>dj :e ~/Dropbox/notes/debugging_journal.txt<cr>
"map <Leader>ec :e ~/code/
"map <Leader>g :Start gitsh<cr>
"map <Leader>gw :!git add . && git commit -m 'WIP' && git push<cr>
"map <Leader>f :call OpenFactoryFile()<CR>
"map <Leader>fix :cnoremap % %<CR>
"map <Leader>fa :sp test/factories.rb<CR>
"map <Leader>i mmgg=G`m
""map <Leader>l oconsole.log 'debugging'<esc>:w<cr>
"map <Leader>m :Rmodel
"map <Leader>mf mmgqap`m:w<cr>
"map <Leader>nn :sp ~/Dropbox/notes/programming_notes.txt<cr>
"map <Leader>nt :e! ~/Dropbox/docs/trailmix/todo.md<cr>
"map <Leader>o :w<cr>:call RunNearestSpec()<CR>
"map <Leader>p :set paste<CR>o<esc>"*]p:set nopaste<cr>
"map <Leader>pn :sp ~/Dropbox/work/thoughtbot/notes/project-notes.md<cr>
"map <Leader>q :copen<cr><cr>
"map <Leader>ra :%s/
"map <Leader>rd :!bundle exec rspec % --format documentation<CR>
"map <Leader>rs :vsp <C-r>#<cr><C-w>w
"map <Leader>rt q:?!ruby<cr><cr>
"map <Leader>rw :%s/\s\+$//<cr>:w<cr>
"map <Leader>sc :sp db/schema.rb<cr>
"map <Leader>sg :sp<cr>:grep<space>
"map <Leader>sj :call OpenJasmineSpecInBrowser()<cr>
"map <Leader>sm :RSmodel
"map <Leader>sp yss<p>
"map <Leader>sn :e ~/.vim/snippets/ruby.snippets<CR>
"map <Leader>so :so %<cr>
"map <Leader>sq j<c-v>}klllcs<esc>:wq<cr>
"map <Leader>ss ds)i <esc>:w<cr>
"map <Leader>st :!ruby -Itest % -n "//"<left><left>
"map <Leader>su :RSunittest
"map <Leader>sv :RSview
"map <Leader>t :w<cr>:call RunCurrentSpecFile()<CR>
"map <Leader>y :!rspec --drb %<cr>
"map <Leader>u :Runittest<cr>
"map <Leader>vc :Vcontroller<cr>
"map <Leader>vf :Vfunctional<cr>
"map <Leader>vg :vsp<cr>:grep
"map <Leader>vi :tabe ~/.vimrc<CR>
"map <Leader>vu :AV<CR>
"map <Leader>vm :Vmodel<cr>
"map <Leader>vv :Vview<cr>
"map <Leader>w <C-w>w
"map <Leader>x :exec getline(".")<cr>

" Edit another file in the same directory as the current file
" uses expression to extract path from current file's path
"map <Leader>e :e <C-R>=escape(expand("%:p:h"),' ') . '/'<CR>
"map <Leader>s :split <C-R>=escape(expand("%:p:h"), ' ') . '/'<CR>
"map <Leader>v :vnew <C-R>=escape(expand("%:p:h"), ' ') . '/'<CR>


" RENAME CURRENT FILE (thanks Gary Bernhardt)
function! RenameFile()
    let old_name = expand('%')
    let new_name = input('New file name: ', expand('%'), 'file')
    if new_name != '' && new_name != old_name
        exec ':saveas ' . new_name
        exec ':silent !rm ' . old_name
        redraw!
    endif
endfunction
"space + n rename filename
map <Leader>n :call RenameFile()<cr>

" Display extra whitespace
set list listchars=tab:»·,trail:·
" By default, vim thinks .md is Modula-2.
"autocmd BufNewFile,BufReadPost *.md set filetype=markdown
" Without this, vim breaks in the middle of words when wrapping
"autocmd FileType markdown setlocal nolist wrap lbr
" Wrap the quickfix window
"autocmd FileType qf setlocal wrap linebreak
" map <Leader>vi :tabe ~/.vim/vimrc<CR>
"比如使用vim –p file1 file2 file3可以打开三个选项卡用于显示3个文件。
"关于选项卡中的操作，如下示：
":tabedit FILENAME
":tabe FILENAME
"在当前vim会话中在另一个选项卡中打开文件
":tabs
"显示所有打开的选项卡
":tabn N
"到第N个选项卡
":tabclose :tabc
"关闭当前选项卡
":tabdo CMD
"对所有的选项卡执行命令CMD
":tabn
"跳转到下一个选项卡
":tabp
"跳转到前一个选项卡
"
map <Leader>vi :!vim ~/.vim/vimrc<CR>
map <Leader>tm :!vim ~/.tmux.conf.local<CR>
map <Leader>ms :!vim ~/.spacemacs<CR>
map <Leader>zs :!vim ~/.zshrc<CR>
map <Leader>mu :!free -g<CR>
" map <Leader>vg :vsp<cr>:grep
map <Leader>vg :vsp<cr>
"map <Leader>t :w<cr>:call RunCurrentSpecFile()<CR>
"map <Leader>sq j<c-v>}klllcs<esc>:wq<cr>
"map <Leader>sg :sp<cr>:grep<space>
"map <Leader>sj :call OpenJasmineSpecInBrowser()<cr>
"map <Leader>so :so %<cr>
"map <Leader>rw :%s/\s\+$//<cr>:w<cr>
"map <Leader>rs :vsp <C-r>#<cr><C-w>w
" open quickfix
"map <Leader>mk :copen<cr>
map <Leader>mk :cw<cr>

"git config
map <Leader>gw :!git add . && git commit -m 'WIP' && git push<cr>
"map <Leader>o :w<cr>:call RunNearestSpec()<CR>
map <Leader>f :call OpenFactoryFile()<CR>
function! OpenFactoryFile()
  if filereadable("test/factories.rb")
    execute ":sp test/factories.rb"
  else
    execute ":sp spec/factories.rb"
  end
endfunction
"map <Leader>cv :Rjview client/
"map <Leader>ct :Rtemplate client/
map <Leader>cl :call SearchForCallSitesCursor()<CR>
function! SearchForCallSitesCursor()
  " let searchTerm = expand("<cword>")
  call SearchForCallSites(searchTerm)
endfunction
"map <Leader>cu :Tabularize /\|<CR>
"map <Leader>cj :Rjspec client/
"map <Leader>cm :Rjmodel client/
"vmap <Leader>b :<C-U>!git blame <C-R>=expand("%:p") <CR> \| sed -n <C-R>=line("'<") <CR>,<C-R>=line("'>") <CR>p <CR>

" Edit another file in the same directory as the current file
" uses expression to extract path from current file's path
map <Leader>e :e <C-R>=escape(expand("%:p:h"),' ') . '/'<CR>
map <Leader>s :split <C-R>=escape(expand("%:p:h"), ' ') . '/'<CR>
map <Leader>v :vnew <C-R>=escape(expand("%:p:h"), ' ') . '/'<CR>

" Make CtrlP use ag for listing the files. Way faster and no useless files.
" Without --hidden, it never finds .travis.yml since it starts with a dot
let g:ctrlp_user_command = 'ag %s -l --hidden --nocolor -g ""'
let g:ctrlp_use_caching = 0
"Now using thoughtbot/vim-rspec and tpope/dispatch.
let g:rspec_command = "Dispatch bin/rspec {spec}"
let g:CommandTMaxHeight=50
let g:CommandTMatchWindowAtTop=1



highlight Folded  guibg=#0A0A0A guifg=#9090D0
" Markdown
autocmd! BufRead *.mkd set ai formatoptions=tcroqn2 comments=n:> ft=markdown
autocmd! BufRead *.md set ai formatoptions=tcroqn2 comments=n:> ft=markdown
autocmd! BufRead *.mdown set ai formatoptions=tcroqn2 comments=n:> ft=markdown
autocmd! BufRead *.markdown set ai formatoptions=tcroqn2 comments=n:> ft=markdown
" CSS3
au BufRead,BufNewFile *.scss set filetype=scss
au BufRead,BufNewFile *.css set ft=css syntax=css

" HTML5
au BufRead,BufNewFile *.html set ft=html syntax=html
au BufRead,BufNewFile *.hbs set ft=html syntax=html
au BufRead,BufNewFile *.mustache set ft=html syntax=html
au BufRead,BufNewFile *.haml set ft=haml

au BufRead,BufNewFile *.js set ft=javascript syntax=javascript
au BufRead,BufNewfile *.rb set ft=ruby syntax=ruby

" The Silver Searcher
if executable("ag")
  " Use ag over Ack
  let g:ackprg = 'ag --nogroup --nocolor --column'

  " Use ag over grep
  set grepprg=ag\ --nogroup\ --nocolor

  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'

  " ag is fast enough that CtrlP doesn't need to cache
  let g:ctrlp_use_caching = 0
endif
"" NERDTree
function! ShowFileInNERDTree()
  if exists("t:NERDTreeBufName")
    NERDTreeFind
  else
    NERDTree
    wincmd l
    NERDTreeFind
  endif
endfunction
map <Leader>d :call ShowFileInNERDTree()<cr>
map <Leader>p :CtrlP<cr>
map <Leader>b :CtrlPBuffer<cr>


"take vim file transform html
map <Leader>ht :TOhtml<cr><esc>:wq<cr>

"jedi python
"NOTE: subject to change!

let g:jedi#goto_command = "<leader>d"
let g:jedi#goto_assignments_command = "<leader>g"
let g:jedi#goto_definitions_command = ""
let g:jedi#documentation_command = "K"
let g:jedi#usages_command = "<leader>n"
let g:jedi#completions_command = "<C-Space>"
let g:jedi#rename_command = "<leader>r"

"	vi +BundleInstall + wq
"  cd YCM
"	python install.py --clang-completer a
"	cp .ycm_confirm_extra_conf ~/
"" ok
"				在普通模式下：
"1.快速定位
"zz :强制把当前光标的文件置于屏幕的中间
"2.来回移动
"ctrl + o:原来的地方
"ctrl + i：返回来上面的跳动
"清除一行，直接进入insert mode
"在每一行开始添加chars
" :%s/^/char/g
"在每一行末尾添加chars
" :%s/$/char/g
"
"1. 包含空行
":%s/$/\\n"/g
"
"2. 不包含空行
":%s/.*\S.*$/&\\n"/g
"

"高效编辑
"di" 光标在”“之间，则删除”“之间的内容
"yi( 光标在()之间，则复制()之间的内容
"vi[ 光标在之间，则选中之间的内容
"以上三种可以自由组合搭配，效率奇高，i(nner)
"dtx 删除字符直到遇见光标之后的第一个x字符
"ytx 复制字符直到遇见光标之后的第一个x字符
"标记和宏(macro)
"ma 将当前位置标记为a，26个字母均可做标记，mb、mc等等；
"'a 跳转到a标记的位置； - 这是一组很好的文档内标记方法，在文档中跳跃编辑时很有用；
"qa 将之后的所有键盘操作录制下来，直到再次在命令模式按下q，并存储在a中；
"@a 执行刚刚记录在a里面的键盘操作；
"@@ 执行上一次的macro操作；'])"





"vim java
" java -jar eclim.jar ok cd eclimpse :./eclim and  vim + PingEclim show success
"http://www.lucianofiandesio.com/vim-configuration-for-happy-java-coding
"http://eclim.org/vim/code_completion.html
"http://eclim.org/eclimd.html
"http://eclim.org/vim/core/project.html
"http://eclim.org/cheatsheet.html

"doxygen toolkit
let g:DoxygenToolkit_briefTag_pre="@Synopsis  "
let g:DoxygenToolkit_paramTag_pre="@Param "
let g:DoxygenToolkit_returnTag="@Returns   "
let g:DoxygenToolkit_blockHeader="----------------------------------"
let g:DoxygenToolkit_blockFooter="----------------------------------"
let g:DoxygenToolkit_authorName="Mathias Lorente"
let g:DoxygenToolkit_licenseTag="My own license"
let g:DoxygenToolkit_authorName="liangkangkang@yahoo.com"
"看了下它的命令，常用的也就是两个：
"光标在函数上，用 :Dox 自动生成函数的说明。
"光标在文件头，用 :DoxAthor 自动生成文件说明
"


"lookupfile usage
"-----------------------------------------------------------------------------
" lookupfile.vim 插件设置
"-----------------------------------------------------------------------------
let g:LookupFile_MinPatLength = 2               "最少输入2个字符才开始查找
let g:LookupFile_PreserveLastPattern = 0        "不保存上次查找的字符串
let g:LookupFile_PreservePatternHistory = 1     "保存查找历史
let g:LookupFile_AlwaysAcceptFirst = 1          "回车打开第一个匹配项目
let g:LookupFile_AllowNewFiles = 0              "不允许创建不存在的文件
let g:LookupFile_SortMethod = ""                "关闭对搜索结果的字母排序
if filereadable("./filenametags")
	let g:LookupFile_TagExpr ='"./filenametags"'
endif

"由于vim工程需要经常建立，故也可以不将下列代码放到vimrc配置文件中，手动切换工程 在vim命令模式下输入配置
"let g:LookupFile_TagExpr ='"/home/filenametags"'

nmap <leader>lf :LookupFile<cr>
"nmap <silent> <leader>lf :LookupFile<cr>
"nmap <leader>ll :LUBufs<cr>
"nmap <leader>lw :LUWald<cr>


"
"
"nmap <leader>fc :cs find c <C-R>=expand("<cword>")<CR><CR>
"nmap <leader>fd :cs find d <C-R>=expand("<cword>")<CR><CR>
"nmap <leader>fe :cs find e <C-R>=expand("<cword>")<CR><CR>
"nmap <leader>ff :cs find f <C-R>=expand("<cfile>")<CR><CR>
"nmap <leader>fg :cs find g <C-R>=expand("<cword>")<CR><CR>
"nmap <leader>fi :cs find i <C-R>=expand("<cfile>")<CR><CR>
"nmap <leader>fs :cs find s <C-R>=expand("<cword>")<CR><CR>
"nmap <leader>ft :cs find t <C-R>=expand("<cword>")<CR><CR>

" man c++
"man namespace::headerman 命名空间::头文件 。通常地：man std::头文件，或man std::函数名，或man std::类名

" ========== omnifunc:javacomplete2 自動補全功能 =========
autocmd FileType java setlocal omnifunc=javacomplete#Complete

" 設定額外 include 的 classpath
"let g:classpath="/home/lkk/first-job/.repo/"
"let g:JavaComplete_LibsPath = "/home/lkk/first-job/.repo"
"let g:JavaComplete_LibsPath = "/home/lkk/spark-1.6.0-bin-hadoop2.6/lib/spark-assembly-1.6.0-hadoop2.6.0.jar"
let g:JavaComplete_LibsPath = "/home/lkk/Downloads/apache-flume-1.7.0-bin/lib/*"

let g:JavaComplete_MavenRepositoryDisable = 1
let g:JavaComplete_UseFQN = 1
let g:JavaComplete_ClosingBrace = 1
let g:JavaComplete_JavaviDebug = 1
let g:JavaComplete_ImportDefault = 0

let g:JavaComplete_ImportSortType = 'jarName'
let g:JavaComplete_ImportOrder = ['java.', 'javax.', 'com.', 'org.', 'net.']

"To enable smart (trying to guess import option) inserting class imports with F10, add:
nmap <F10> <Plug>(JavaComplete-Imports-AddSmart)
imap <F10> <Plug>(JavaComplete-Imports-AddSmart)

"To enable inserting class imports with F2, add:
nmap <F2> <Plug>(JavaComplete-Imports-Add)
imap <F2> <Plug>(JavaComplete-Imports-Add)

"To add all missing imports with F8:
nmap <F8> <Plug>(JavaComplete-Imports-AddMissing)
imap <F8> <Plug>(JavaComplete-Imports-AddMissing)

"To remove all missing imports with F9:
nmap <F9> <Plug>(JavaComplete-Imports-RemoveUnused)
imap <F9> <Plug>(JavaComplete-Imports-RemoveUnused)


" ========== omnifunc:javacomplete 自動補全功能 =========
" 設定此行在 java 檔案中，就可按(ctrl + x) + (ctrl + o) 自動補全
setlocal omnifunc=javacomplete#Complete

" 當檔案為副檔名為 java 動作
" mode的狀態下,按"."會替換成以下指令，換言之，與ide相同當按"."會自動補全
autocmd Filetype java,jsp set omnifunc=javacomplete#Complete
autocmd Filetype java,jsp set completefunc=javacomplete#CompleteParamsInf
autocmd Filetype java,jsp inoremap &lt;buffer> . .&lt;C-X>&lt;C-O>&lt;C-P>&lt;DOWN>

